<template>
  <header class="app-header" :class="headerClass">
    <div class="header-container">
      <!-- Logo 区域 -->
      <div class="header-logo">
        <router-link to="/" class="logo-link">
          <img src="@/assets/logo.png" alt="Logo" class="logo-image" />
          <span class="logo-text">在线学习平台</span>
        </router-link>
      </div>

      <!-- 导航菜单 -->
      <nav class="header-nav" v-if="!isMobile">
        <ul class="nav-list">
          <li class="nav-item" v-for="item in navItems" :key="item.path">
            <router-link 
              :to="item.path" 
              class="nav-link"
              :class="{ active: $route.path === item.path }"
            >
              <i :class="item.icon" v-if="item.icon"></i>
              {{ item.title }}
            </router-link>
          </li>
        </ul>
      </nav>

      <!-- 搜索框 -->
      <div class="header-search" v-if="!isMobile">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索课程、考试..."
          class="search-input"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <!-- 用户操作区域 -->
      <div class="header-actions">
        <!-- 主题切换 -->
        <el-tooltip content="切换主题" placement="bottom">
          <el-button 
            circle 
            @click="toggleTheme"
            class="action-btn theme-btn"
          >
            <el-icon>
              <Sunny v-if="themeStore.isDark" />
              <Moon v-else />
            </el-icon>
          </el-button>
        </el-tooltip>

        <!-- 通知 -->
        <el-dropdown trigger="click" v-if="userStore.isLoggedIn">
          <el-badge :value="unreadCount" :hidden="unreadCount === 0">
            <el-button circle class="action-btn">
              <el-icon><Bell /></el-icon>
            </el-button>
          </el-badge>
          <template #dropdown>
            <el-dropdown-menu class="notification-dropdown">
              <div class="notification-header">
                <span>通知消息</span>
                <el-button text size="small" @click="markAllAsRead">全部已读</el-button>
              </div>
              <div class="notification-list">
                <div 
                  v-for="notification in notifications" 
                  :key="notification.id"
                  class="notification-item"
                  :class="{ unread: !notification.read }"
                  @click="handleNotificationClick(notification)"
                >
                  <div class="notification-content">
                    <div class="notification-title">{{ notification.title }}</div>
                    <div class="notification-desc">{{ notification.content }}</div>
                    <div class="notification-time">{{ formatTime(notification.createdAt) }}</div>
                  </div>
                </div>
                <div v-if="notifications.length === 0" class="notification-empty">
                  暂无通知
                </div>
              </div>
              <div class="notification-footer">
                <el-button text @click="viewAllNotifications">查看全部</el-button>
              </div>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <!-- 用户菜单 -->
        <div class="user-menu" v-if="userStore.isLoggedIn">
          <el-dropdown trigger="click">
            <div class="user-info">
              <el-avatar :src="userStore.userInfo?.avatar" :size="32">
                {{ userStore.userInfo?.nickname?.charAt(0) || 'U' }}
              </el-avatar>
              <span class="username" v-if="!isMobile">{{ userStore.userInfo?.nickname }}</span>
              <el-icon class="dropdown-icon"><ArrowDown /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="$router.push('/profile')">
                  <el-icon><User /></el-icon>
                  个人中心
                </el-dropdown-item>
                <el-dropdown-item @click="$router.push('/my-courses')">
                  <el-icon><Reading /></el-icon>
                  我的课程
                </el-dropdown-item>
                <el-dropdown-item @click="$router.push('/my-exams')">
                  <el-icon><Document /></el-icon>
                  我的考试
                </el-dropdown-item>
                <el-dropdown-item @click="$router.push('/favorites')">
                  <el-icon><Star /></el-icon>
                  我的收藏
                </el-dropdown-item>
                <el-dropdown-item @click="$router.push('/settings')">
                  <el-icon><Setting /></el-icon>
                  设置
                </el-dropdown-item>
                <el-dropdown-item divided @click="handleLogout">
                  <el-icon><SwitchButton /></el-icon>
                  退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>

        <!-- 登录/注册按钮 -->
        <div class="auth-buttons" v-else>
          <el-button @click="$router.push('/login')" text>登录</el-button>
          <el-button @click="$router.push('/register')" type="primary">注册</el-button>
        </div>

        <!-- 移动端菜单按钮 -->
        <el-button 
          v-if="isMobile" 
          circle 
          @click="toggleMobileMenu"
          class="action-btn mobile-menu-btn"
        >
          <el-icon><Menu /></el-icon>
        </el-button>
      </div>
    </div>

    <!-- 移动端菜单 -->
    <div class="mobile-menu" v-if="isMobile && showMobileMenu">
      <div class="mobile-search">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索课程、考试..."
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      <ul class="mobile-nav-list">
        <li class="mobile-nav-item" v-for="item in navItems" :key="item.path">
          <router-link 
            :to="item.path" 
            class="mobile-nav-link"
            @click="showMobileMenu = false"
          >
            <i :class="item.icon" v-if="item.icon"></i>
            {{ item.title }}
          </router-link>
        </li>
      </ul>
    </div>
  </header>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Bell,
  User,
  Reading,
  Document,
  Star,
  Setting,
  SwitchButton,
  ArrowDown,
  Sunny,
  Moon,
  Menu
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { useThemeStore } from '@/stores/theme'
import { useAppStore } from '@/stores/app'
import { formatRelativeTime } from '@/utils'

const router = useRouter()
const userStore = useUserStore()
const themeStore = useThemeStore()
const appStore = useAppStore()

// 响应式数据
const searchKeyword = ref('')
const showMobileMenu = ref(false)
const notifications = ref([])
const unreadCount = ref(0)

// 导航菜单项
const navItems = [
  { path: '/', title: '首页', icon: 'el-icon-house' },
  { path: '/courses', title: '课程', icon: 'el-icon-reading' },
  { path: '/exams', title: '考试', icon: 'el-icon-document' },
  { path: '/about', title: '关于', icon: 'el-icon-info' }
]

// 计算属性
const isMobile = computed(() => appStore.isMobile)
const headerClass = computed(() => ({
  'is-mobile': isMobile.value,
  'is-scrolled': appStore.isScrolled
}))

// 方法
const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    router.push({
      path: '/search',
      query: { q: searchKeyword.value.trim() }
    })
    searchKeyword.value = ''
    showMobileMenu.value = false
  }
}

const toggleTheme = () => {
  themeStore.toggleTheme()
}

const toggleMobileMenu = () => {
  showMobileMenu.value = !showMobileMenu.value
}

const handleLogout = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要退出登录吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await userStore.logout()
    ElMessage.success('退出登录成功')
    router.push('/')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('退出登录失败:', error)
      ElMessage.error('退出登录失败')
    }
  }
}

const handleNotificationClick = (notification) => {
  // 标记为已读
  if (!notification.read) {
    notification.read = true
    unreadCount.value--
  }
  
  // 跳转到相关页面
  if (notification.link) {
    router.push(notification.link)
  }
}

const markAllAsRead = () => {
  notifications.value.forEach(notification => {
    notification.read = true
  })
  unreadCount.value = 0
}

const viewAllNotifications = () => {
  router.push('/notifications')
}

const formatTime = (time) => {
  return formatRelativeTime(time)
}

const loadNotifications = async () => {
  try {
    // 这里应该调用 API 获取通知数据
    // const response = await notificationApi.getNotifications()
    // notifications.value = response.data
    // unreadCount.value = response.data.filter(n => !n.read).length
    
    // 模拟数据
    notifications.value = [
      {
        id: 1,
        title: '课程更新',
        content: 'Vue.js 进阶课程已更新第10章',
        createdAt: new Date(Date.now() - 1000 * 60 * 30),
        read: false,
        link: '/courses/1'
      },
      {
        id: 2,
        title: '考试提醒',
        content: 'JavaScript 基础考试将在明天开始',
        createdAt: new Date(Date.now() - 1000 * 60 * 60 * 2),
        read: false,
        link: '/exams/1'
      }
    ]
    unreadCount.value = notifications.value.filter(n => !n.read).length
  } catch (error) {
    console.error('加载通知失败:', error)
  }
}

// 监听滚动事件
const handleScroll = () => {
  appStore.setScrolled(window.scrollY > 0)
}

// 生命周期
onMounted(() => {
  if (userStore.isLoggedIn) {
    loadNotifications()
  }
  window.addEventListener('scroll', handleScroll)
})

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})
</script>

<style lang="scss" scoped>
.app-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  background: var(--el-bg-color);
  border-bottom: 1px solid var(--el-border-color-light);
  transition: all 0.3s ease;
  backdrop-filter: blur(10px);
  
  &.is-scrolled {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
  
  .header-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  
  .header-logo {
    .logo-link {
      display: flex;
      align-items: center;
      text-decoration: none;
      color: var(--el-text-color-primary);
      
      .logo-image {
        height: 32px;
        margin-right: 8px;
      }
      
      .logo-text {
        font-size: 18px;
        font-weight: 600;
      }
    }
  }
  
  .header-nav {
    flex: 1;
    margin: 0 40px;
    
    .nav-list {
      display: flex;
      list-style: none;
      margin: 0;
      padding: 0;
      
      .nav-item {
        margin-right: 32px;
        
        .nav-link {
          display: flex;
          align-items: center;
          padding: 8px 0;
          text-decoration: none;
          color: var(--el-text-color-regular);
          font-weight: 500;
          transition: color 0.3s ease;
          
          i {
            margin-right: 4px;
          }
          
          &:hover,
          &.active {
            color: var(--el-color-primary);
          }
        }
      }
    }
  }
  
  .header-search {
    width: 300px;
    
    .search-input {
      :deep(.el-input__wrapper) {
        border-radius: 20px;
      }
    }
  }
  
  .header-actions {
    display: flex;
    align-items: center;
    gap: 12px;
    
    .action-btn {
      width: 36px;
      height: 36px;
      border: none;
      background: transparent;
      color: var(--el-text-color-regular);
      
      &:hover {
        background: var(--el-fill-color-light);
        color: var(--el-color-primary);
      }
    }
    
    .user-menu {
      .user-info {
        display: flex;
        align-items: center;
        cursor: pointer;
        padding: 4px 8px;
        border-radius: 20px;
        transition: background-color 0.3s ease;
        
        &:hover {
          background: var(--el-fill-color-light);
        }
        
        .username {
          margin: 0 8px;
          font-weight: 500;
          color: var(--el-text-color-primary);
        }
        
        .dropdown-icon {
          color: var(--el-text-color-regular);
          transition: transform 0.3s ease;
        }
      }
    }
    
    .auth-buttons {
      display: flex;
      gap: 8px;
    }
  }
  
  // 移动端样式
  &.is-mobile {
    .header-container {
      padding: 0 16px;
    }
    
    .header-nav,
    .header-search {
      display: none;
    }
    
    .logo-text {
      display: none;
    }
  }
  
  .mobile-menu {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background: var(--el-bg-color);
    border-bottom: 1px solid var(--el-border-color-light);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    
    .mobile-search {
      padding: 16px;
    }
    
    .mobile-nav-list {
      list-style: none;
      margin: 0;
      padding: 0;
      
      .mobile-nav-item {
        .mobile-nav-link {
          display: flex;
          align-items: center;
          padding: 16px;
          text-decoration: none;
          color: var(--el-text-color-primary);
          border-bottom: 1px solid var(--el-border-color-lighter);
          
          i {
            margin-right: 8px;
          }
          
          &:hover {
            background: var(--el-fill-color-light);
          }
        }
      }
    }
  }
}

// 通知下拉菜单样式
.notification-dropdown {
  width: 320px;
  max-height: 400px;
  
  .notification-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    border-bottom: 1px solid var(--el-border-color-lighter);
    font-weight: 600;
  }
  
  .notification-list {
    max-height: 300px;
    overflow-y: auto;
    
    .notification-item {
      padding: 12px 16px;
      border-bottom: 1px solid var(--el-border-color-lighter);
      cursor: pointer;
      transition: background-color 0.3s ease;
      
      &:hover {
        background: var(--el-fill-color-light);
      }
      
      &.unread {
        background: var(--el-color-primary-light-9);
        
        &::before {
          content: '';
          position: absolute;
          left: 8px;
          top: 50%;
          transform: translateY(-50%);
          width: 6px;
          height: 6px;
          border-radius: 50%;
          background: var(--el-color-primary);
        }
      }
      
      .notification-content {
        .notification-title {
          font-weight: 500;
          margin-bottom: 4px;
          color: var(--el-text-color-primary);
        }
        
        .notification-desc {
          font-size: 12px;
          color: var(--el-text-color-regular);
          margin-bottom: 4px;
          line-height: 1.4;
        }
        
        .notification-time {
          font-size: 11px;
          color: var(--el-text-color-placeholder);
        }
      }
    }
    
    .notification-empty {
      padding: 40px 16px;
      text-align: center;
      color: var(--el-text-color-placeholder);
    }
  }
  
  .notification-footer {
    padding: 8px 16px;
    text-align: center;
    border-top: 1px solid var(--el-border-color-lighter);
  }
}
</style>